//
//  NewsIformationController.m
//  华康通
//
//  Created by 雷雨 on 16/4/19.
//  Copyright © 2016年 华康集团. All rights reserved.
//

#import "NewsIformationController.h"
#import "TitleView.h"
#import "VidoCollectionCell.h"
#import "TRNews.h"
#import "NewsIformationDetailController.h"
#import "UIImageView+WebCache.h"
#import "objc/runtime.h"
#import "UIView+WebCacheOperation.h"

@interface NewsIformationController ()
@property (nonatomic, strong) TitleView* titleView;
@property (nonatomic, strong) NSArray* bigTypes;
//点击最上面的滚动按钮的index
@property (unsafe_unretained, nonatomic) NSInteger topIndex;

@property (nonatomic, strong) NSArray* newsDatas;
@property (nonatomic, strong) ShowNoNetworkView* workView;
@property (nonatomic, strong) MJRefreshGifHeader *header;


@end

@implementation NewsIformationController

- (NSArray*)bigTypes
{
    if (!_bigTypes)
    {
        _bigTypes = @[@"华康新闻",@"监管动态",@"行业动态"];
    }
    return _bigTypes;
}
- (TitleView*)titleView
{
    if (!_titleView)
    {
        _titleView = [[TitleView alloc]initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width - 100, 44)];
        _titleView.backgroundColor = ClEARColor;
    }
    return _titleView;
}
- (void)viewDidLoad
{
    [super viewDidLoad];
    self.topIndex = 0;
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithImage:LoadImage(@"back1") style:UIBarButtonItemStylePlain target:self action:@selector(popRootVC)];
    [self.tableView registerNib:[UINib nibWithNibName:@"VidoCollectionCell" bundle:nil] forCellReuseIdentifier:@"cell"];
    self.titleView.buttonTitles = self.bigTypes;
    self.navigationItem.titleView = self.titleView;
    [self.titleView scrollView];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(buttonChange3:) name:@"buttonChange3" object:nil];
    self.header = [MJRefreshGifHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewData)];
    self.header.lastUpdatedTimeLabel.hidden = YES;
    self.tableView.header = self.header;
    [self postNewsListWithType:[NSString stringWithFormat:@"%ld",(long)self.topIndex + 1]];
}

//下拉刷新
- (void)loadNewData
{
    NSLog(@"下拉刷新");
    [self.tableView.header beginRefreshing];
    [self.tableView.footer resetNoMoreData];
    dispatch_time_t delay = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC));
    dispatch_after(delay, dispatch_get_main_queue(), ^{
        //请求数据
        [self postNewsListWithType:[NSString stringWithFormat:@"%ld",(long)self.topIndex + 1]];
    });
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [MobClick beginLogPageView:@"NewsIformationController"];//("PageOne"为页面名称，可自定义)
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [SVProgressHUD dismiss];
    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
    [MobClick endLogPageView:@"NewsIformationController"];
}

#pragma mark  //获取新闻列表

- (void)postNewsListWithType:(NSString*)type
{
    //设置缓存的key
    NSString* cacheStr;
    cacheStr = [NSString stringWithFormat:@"getNewsList_type%ld",(long)type];
    NSString* str;
    if ([type isEqualToString:@"1"])
    {
        str = @"5493938404675330";
    }
    else if ([type isEqualToString:@"2"])
    {
        str = @"5493938519222890";
    }
    else if ([type isEqualToString:@"3"])
    {
        str = @"5493938461255790";
    }
    else
    {
        str = @"1";
    }
    NSDictionary* json = @{@"platformType":@"1",
             @"orderType":@"01",
             @"requestService":@"getNewsList",
             @"requestObject":@{@"newType":str}
             };
    NSLog(@"json = %@",json);
    //字符串转字符串
    NSString* jsonStr = [JSONToString dictionaryToJson:json];
    //转md5
    MyAdditions* md5 = [[MyAdditions alloc]init];
    md5.str = [NSString stringWithFormat:@"%@%@",KEY_POST,jsonStr];
    NSString* md5_Str = [md5 md5];
    NSString* url = [NSString stringWithFormat:@"%@&sign=%@",SERVER_URL,md5_Str];
    [self getNewsListWithURL:url withParam:json withCacheStr:cacheStr];
}

//读取网络或本地的订单列表数据
- (void)readNewsListWithData:(NSData*)data
{
    id json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
    NSLog(@"获取新闻列表json = %@",json);
    if ([json isKindOfClass:[NSDictionary class]] && json)
    {
        if ([json[@"resultCode"] isEqualToString:@"0"])
        {
            dispatch_async(dispatch_get_global_queue(0, 0), ^{
                
                NSMutableArray* arr = [NSMutableArray array];
                for (NSDictionary* dict in json[@"responseObject"][@"newList"])
                {
                    TRNews* news = [TRNews newsWithJSON:dict];
                    [arr addObject:news];
                }
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self endRefresh];
                    self.newsDatas = [arr copy];
                    [self.tableView reloadData];
                    [self jugdeShowWorkView];
                });
            });
            
        }
        else
        {
            
            dispatch_async(dispatch_get_main_queue(), ^{
                [self jugdeShowWorkView];
                [self endRefresh];
            });
        }
    }
}

/**
 *  停止刷新
 */

-(void)endRefresh
{
    if ([self.tableView.header isRefreshing])
    {
        [self.tableView.header endRefreshing];
    }
    if ([self.tableView.footer isRefreshing])
    {
        [self.tableView.footer endRefreshing];
    }
}

- (void)createWorkView
{
    if (self.workView == nil)
    {
        self.workView = [[ShowNoNetworkView alloc]initWithFrame:CGRectMake(0, 40, UISCREENWEITH, self.tableView.frame.size.height)];
        self.workView.labelText = @"暂无记录";
        self.workView.imageName = @"no_record";
        self.workView.myType = MyTypeOfViewForShowError;
        [self.workView createAllSubView];
        [self.view addSubview:self.workView];
    }
}

- (void)removeWorkView
{
    self.workView.frame = CGRectZero;
    [self.workView removeFromSuperview];
    self.workView = nil;
}

//如果没有列表数据就显示一个提示view
- (void)jugdeShowWorkView
{
    if (self.newsDatas.count == 0)
    {
        [self createWorkView];
    }
    else
    {
        [self removeWorkView];
    }
}

- (void)getNewsListWithURL:(NSString*)url withParam:(NSDictionary*)param withCacheStr:(NSString*)cacheStr
{
    NSLog(@"cacheStr = %@",cacheStr);
    
    HKTShowNetworkView* networking = [HKTShowNetworkView shareInstanceWithTitle:@"检测到您的设备没有连接网络!" withImageStr:@"no_record" withType:0 withFrame:CGRectMake(0, StatusBarHeight + NavigationBarHeight, UISCREENWEITH, UISCREENHEIGHT - StatusBarHeight - NavigationBarHeight) withVC:self];
    [networking showNetworkViewWithSuccess:^{
        self.tableView.scrollEnabled = YES;
        [self.header setHidden:NO];
        
        [XHNetworking POST:url parameters:param cacheStr:cacheStr jsonCache:^(id jsonCache) {
            //无网络得到缓存 从缓存读取缓存信息;
            [self readNewsListWithData:jsonCache];
        } success:^(NSData *responseObject) {
            //网络读取数据
            [self readNewsListWithData:responseObject];
        } failure:^(NSError *error) {
            //        [self endRefresh];
            NSLog(@"error.code = %@",error.userInfo);
            dispatch_async(dispatch_get_main_queue(), ^{
                [self endRefresh];
                [self jugdeShowWorkView];
            });
        }];
        
    } failure:^{
        
        dispatch_async(dispatch_get_main_queue(), ^{
            self.tableView.scrollEnabled = NO;
            [self.header setHidden:YES];
        });
        
    } click:^(NSInteger type) {
        if (type == 0)
        {
            //弹出网络提示
            
        }
    }];
    
}

- (void)viewWillLayoutSubviews
{
    
}

- (void)buttonChange3:(NSNotification*)notification
{
    [self.tableView setScrollsToTop:YES];
    
    self.topIndex = [notification.userInfo[@"buttonTag"] integerValue];
    NSLog(@"%ld",(long)self.topIndex);
    [self postNewsListWithType:[NSString stringWithFormat:@"%ld",(long)self.topIndex + 1]];
}

- (void)popRootVC
{
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.newsDatas.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 90.0;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    VidoCollectionCell* cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
    cell.myImageView.layer.borderColor = [UIColor colorWithRed:248.0/255.0 green:248.0/255.0 blue:248.0/255.0 alpha:1.0].CGColor;
    cell.myImageView.layer.borderWidth = 1.0;
    TRNews* news = self.newsDatas[indexPath.row];
    cell.topLabel.text = news.titleInformation;
    cell.bottomLabel.text = news.detailInformation;
    [cell.myImageView sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",IMAGE_URL,news.imageInformation]]
                      placeholderImage:LoadImage(@"500.png")];
    if ([news.imageInformation rangeOfString:HTTP].location != NSNotFound)
    {
        [cell.myImageView sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",news.imageInformation]]
                            placeholderImage:LoadImage(@"500.png")];
    }
    return cell;
}
//推出新闻详情页面
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    TRNews* news = self.newsDatas[indexPath.row];
    NewsIformationDetailController* newDetailVC = [[NewsIformationDetailController alloc]initWithNibName:@"NewsIformationDetailController" bundle:nil];
    newDetailVC.isPush = YES;
    newDetailVC.url = [NSString stringWithFormat:@"%@/static/news/detail.html?newsid=%@",NEWS_URL,news.smallTitleInformation];
    [self.navigationController pushViewController:newDetailVC animated:YES];
}

- (void)viewDidDisappear:(BOOL)animated
{
    
}
@end
